#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
FFMPEG_DIR="$GLOBAL_TOOLS_DIR/ffmpeg"

mkdir -p "$FFMPEG_DIR"
if [ -d "$FFMPEG_DIR" ]; then
  echo "FFMPEG_DIR Dir: "$FFMPEG_DIR
else
  echo "Error, FFMPEG Dir dose not exist, please retry. "$FFMPEG_DIR
  exit 1
fi

DOWNLOAD_HOST=https://registry.npmmirror.com/-/binary/ffmpeg-static/b6.0/

function download_ffmpeg_and_ffprobe {
  if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    # echo "macOS system."
    hardware_type=$(uname -m)
    if [[ "$hardware_type" == "arm64" ]]; then
        INSTALLER_URL_FFMPEG=${DOWNLOAD_HOST}ffmpeg-darwin-arm64
        INSTALLER_URL_FFPROBE=${DOWNLOAD_HOST}ffprobe-darwin-arm64
    elif [[ "$hardware_type" == "x86_64" ]]; then
        INSTALLER_URL_FFMPEG=${DOWNLOAD_HOST}ffmpeg-darwin-x64
        INSTALLER_URL_FFPROBE=${DOWNLOAD_HOST}ffprobe-darwin-x64
    fi

    FFMPEG_SAVE_FILE_NAME=ffmpeg
    FFPROBE_SAVE_FILE_NAME=ffprobe

  elif current_os_is_windows; then
    # echo "Windows system."
    INSTALLER_URL_FFMPEG=${DOWNLOAD_HOST}ffmpeg-win32-x64
    INSTALLER_URL_FFPROBE=${DOWNLOAD_HOST}ffprobe-win32-x64

    FFMPEG_SAVE_FILE_NAME=ffmpeg.exe
    FFPROBE_SAVE_FILE_NAME=ffprobe.exe
  fi


  export FFMPEG_BIN_PATH="$FFMPEG_DIR/$FFMPEG_SAVE_FILE_NAME"
  export FFPROBE_BIN_PATH="$FFMPEG_DIR/$FFPROBE_SAVE_FILE_NAME"

  echo $FFMPEG_BIN_PATH $INSTALLER_URL_FFMPEG
  rm -f "$FFMPEG_BIN_PATH"
  curl --ssl-no-revoke -L -C - --retry 7 -o "$FFMPEG_BIN_PATH" $INSTALLER_URL_FFMPEG
  chmod +x "$FFMPEG_BIN_PATH"

  rm -f "$FFPROBE_BIN_PATH"
  curl --ssl-no-revoke -L -C - --retry 7 -o "$FFPROBE_BIN_PATH" $INSTALLER_URL_FFPROBE
  chmod +x "$FFPROBE_BIN_PATH"
}

download_ffmpeg_and_ffprobe